#include <REGX52.H>
#include <intrins.h>
#include <string.h>

#define SIZE 45


sfr AUXR = 0x8e;
sbit D5 = P3^7;
sbit D6 = P3^6;
		

char buffer[SIZE];
char RST[]         = "AT+RST\r\n";    //重启WIFI模块
code char C_WIFI[] = "AT+CWJAP=\"CMCC-6618\",\"13882396618\"\r\n";     //链接WIFI
code char Severs[] = "AT+CIPSTART=\"TCP\",\"192.168.1.25\",8880\r\n";   //连入服务器
char GFP_T[]       = "AT+CIPMODE=1\r\n";     //开启透传模式
char Strmsg[]      = "AT+CIPSEND\r\n";      //开始数据传输   

char Mark_WIFI = 0;
char Mark_OK = 0;
int j;

void Delay1000ms()		//@11.0592MHz
{
	unsigned char i, j, k;

	_nop_();
	i = 8;
	j = 1;
	k = 243;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}


void InitUart(){

	AUXR  = 0x01;
	SCON  = 0x50;
	TMOD &= 0xF0;
	TMOD |= 0x20;
	
	TH1   = 0xFD;
	TL1   = 0xFD;
	TR1   = 1;
	
	EA    = 1;
	ES    = 1;

}

void SendByte(char data_masg){
	
	SBUF = data_masg;
	while(!TI);
	TI = 0;
}

void Sendstring(char* str){

	while( *str != '\0'){
		
		SendByte(*str);
		str++;
	}
}

int main(){
	
	D5 = D6 =1;
	InitUart();
	Delay1000ms();
	Delay1000ms();	//等待上电
	
	Sendstring(RST);
	while(!Mark_OK);
	Mark_OK = 0;

	//等待WIFI连接
	Sendstring(C_WIFI);
	while(!Mark_WIFI);

	D5 = 0;
	Delay1000ms();
	Delay1000ms();
	D5 = 1;	
	
	//等待连接服务器
	Sendstring(Severs);
	while(!Mark_OK);
	Mark_OK = 0;
	//设置透传模式
	Sendstring(GFP_T);
	while(!Mark_OK);
	Mark_OK = 0;
	//开始传输数据
	Sendstring(Strmsg);
	while(!Mark_OK);

	
	//如果WIFI连接成功，D5亮
	if(Mark_WIFI){
		D5 = 0;
	}
	
	//连接服务器打开透传模式成功,D6亮
	if(Mark_OK){
		D6 = 0;
	}
		
	//心跳包
	while(1){
		Delay1000ms();
		Sendstring("xl666\r\n");
	}
}

void Uart_Handler() interrupt 4
{	
	char tmp = 0;
	static int i = 0;
	
	if(RI)//中断处理函数中，对于接收中断的响应
	{
		RI = 0;//清除接收中断标志位
		tmp = SBUF;//临时变量接收第一位数据
		
		//位置预设，将传进来的相关数据置位为第0位
		if(tmp == 'O' || tmp == 'L' || tmp == 'A' || tmp == 'E' || tmp == 'W'){
			i = 0;
		}
		buffer[i++] = tmp;
		
		if(buffer[0] == 'W' && buffer[5] == 'G'){
			Mark_WIFI = 1;
			memset(buffer, '\0', SIZE);
		}
		
		if(buffer[0] == 'E' && buffer[2] == 'R'){
			
			for(j = 0; j < 3; j++){
				D6 = 0;
				Delay1000ms();
				D6 = 1;
			}
			Sendstring(RST);
			memset(buffer, '\0', SIZE);
		}
		
		if( buffer[1] == 'A' && buffer[3] == 'L'){
			
			for(i=0;i<5;i++){
				D5 = 0;
				Delay1000ms();
				D5 = 1;
				Delay1000ms();
			}
			Sendstring(RST);
			memset(buffer, '\0', SIZE);
		}
		
		
		
		if(buffer[0] == 'O' && buffer[1] == 'K'){	
			Mark_OK = 1;
			memset(buffer, '\0', SIZE);
		}
		
		if(buffer[0] == 'L' && buffer[2] == '1' ){
			D5 = 0;//点亮D5
			memset(buffer, '\0', SIZE);
		}
		if(buffer[0] == 'L' && buffer[2] == '0'){
			D5 = 1;//熄灭D5
			memset(buffer, '\0', SIZE);
		}
		if(i == SIZE) 
		{i = 0;}
	}
	
}